package com.liuyucheng.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;

@Slf4j
public class CommandExecutor {

    /**
     * 执行本地命令并返回输出结果
     *
     * @param command 命令及参数数组（例如：new String[]{"cmd", "/c", "dir"}）
     * @return 命令的输出结果
     * @throws IOException          如果发生I/O错误
     * @throws InterruptedException 如果执行被中断
     * @throws RuntimeException     如果命令执行返回非零状态码
     */
    public static String executeCommand(String... command) throws IOException, InterruptedException {
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        Process process = processBuilder.start();

        // 创建线程分别读取输入流和错误流
        StreamConsumer inputConsumer = new StreamConsumer(process.getInputStream());
        StreamConsumer errorConsumer = new StreamConsumer(process.getErrorStream());
        inputConsumer.start();
        errorConsumer.start();

        int exitCode = process.waitFor();
        inputConsumer.join();
        errorConsumer.join();

        String output = inputConsumer.getOutput();
        String error = errorConsumer.getOutput();

        // 如果命令执行失败，抛出异常
        if (exitCode != 0) {
            throw new RuntimeException(
                    "命令执行失败，退出码: " + exitCode + "\n" +
                            "错误信息:\n" + error
            );
        }

        return output;
    }

    // 内部类用于异步读取流
    private static class StreamConsumer extends Thread {
        private final InputStream inputStream;
        private final StringBuilder output;

        public StreamConsumer(InputStream inputStream) {
            this.inputStream = inputStream;
            this.output = new StringBuilder();
        }

        @Override
        public void run() {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line).append("\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public String getOutput() {
            return output.toString().trim(); // 去除末尾空行
        }
    }

    public static String convertGBKtoUTF8(String gbkStr) throws UnsupportedEncodingException {
        byte[] gbkBytes = gbkStr.getBytes("GBK");
        String unicodeStr = new String(gbkBytes, "GBK");
        byte[] utf8Bytes = unicodeStr.getBytes(StandardCharsets.UTF_8);
        return new String(utf8Bytes, StandardCharsets.UTF_8);
    }


    // 示例用法
    public static void main(String[] args) throws IOException, InterruptedException {
//        try {
//            // 执行dir命令（Windows）
//            String result = executeCommand("ipconfig");
//            System.out.println("命令输出:\n" + convertGBKtoUTF8(result));
//
//            // 执行echo命令（跨平台）
//            // String result = executeCommand("echo", "Hello, World!");
//        } catch (IOException | InterruptedException e) {
//            e.printStackTrace();
//        } catch (RuntimeException e) {
//            System.err.println("命令执行错误: " + e.getMessage());
//        }

        File file = new File("C:\\Users\\LiuYucheng\\Desktop\\credit_card\\assets\\js");
        File[] files = file.listFiles();
        String line = "";
        for (File f : files) {
            String fileName = f.getName();
            if (fileName.endsWith(".js")) {
//                log.info("开始处理文件：{}", fileName);
                String command = "npx javascript-obfuscator \"C:\\Users\\LiuYucheng\\Desktop\\credit_card\\assets\\js\\app~748942c6.a96c2ccb.js\" --output \"C:\\Users\\LiuYucheng\\Desktop\\temp\\app~748942c6.a96c2ccb.js\"";
                String result = executeCommand(command);
                System.out.println("命令输出:\n" + result);
                System.out.println(command);
            }
        }
        System.out.println(line);
        log.info("处理完成");
    }
}
